﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using NSsh.Common.Packets;
using NSsh.Common.Types;
using System.IO;
using NUnit.Framework.SyntaxHelpers;
using NSsh.Common.Utility;

namespace NSsh.Common.Tests.Packets
{
    [TestFixture]
    public class DisconnectPacketFixture
    {
        [SetUp]
        public void Setup()
        {
            Dependency.Clear();
            Dependency.RegisterTransient<ISecureRandom, SecureRandom>("SecureRandom");
        }

        [Test]
        public void ShouldCreateFromPacketType()
        {
            Packet packet = new DisconnectPacket();
            Assert.That(packet.PacketType, Is.EqualTo(PacketType.Disconnect), "Incorrect packet type.");
        }

        [Test]
        public void ShouldCreateFromBinaryReader()
        {
            int length = 123;
            int paddingLength = 5;
            byte[] randomPadding = { 0, 1, 2, 3, 4 };
            string languageTag = "languageTag";
            string description = "description";
            DisconnectReason disconnectReason = DisconnectReason.ByApplication;
            MemoryStream memoryStream = new MemoryStream();

            BinaryWriter writer = new BinaryWriter(memoryStream);
            writer.WriteBE((uint)length);
            writer.Write((byte)paddingLength);

            writer.Write((byte)PacketType.Disconnect);

            writer.Write((uint) disconnectReason);
            writer.Write(new SshString(description, Encoding.UTF8).ToByteArray());
            writer.Write(new SshString(languageTag, Encoding.ASCII).ToByteArray());

            writer.Write(randomPadding);

            // Reset the stream
            memoryStream.Seek(0, SeekOrigin.Begin);

            // Create from the binary reader
            BinaryReader reader = new BinaryReader(memoryStream);
            DisconnectPacket disconnectPacket = new DisconnectPacket(new SshPacketContext(reader));

            Assert.That(disconnectPacket.DisconnectReason, Is.EqualTo(disconnectReason));
            Assert.That(disconnectPacket.Description, Is.EqualTo(description));
            Assert.That(disconnectPacket.LanguageTag, Is.EqualTo(languageTag));

            PacketFixture.ComparePacketByteData(disconnectPacket, memoryStream);
        }
    }
}
